package org.feng.fxfront.util;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.feng.api.PageBean;
import org.feng.api.PageRequest;
import org.feng.api.ResultVo;

import java.util.concurrent.TimeUnit;

/**
 * OKHttp工具
 */
@Slf4j
public class OkHttpUtil {

    public static final String MEDIA_TYPE_JSON = "application/json; charset=utf-8";

    private OkHttpUtil() {
    }

    /**
     * 获取默认的OkHttpClient
     */
    public static OkHttpClient getOkHttpClient() {
        return getOkHttpClient(60, 60, 60);
    }

    public static OkHttpClient getOkHttpClient(int connectTimeout, int readTimeOut, int writeTimeOut) {
        OkHttpClient.Builder builder = new okhttp3.OkHttpClient().newBuilder();
        builder.connectTimeout(connectTimeout, TimeUnit.SECONDS);
        builder.readTimeout(readTimeOut, TimeUnit.SECONDS);
        builder.writeTimeout(writeTimeOut, TimeUnit.SECONDS);
        return builder.build();
    }

    /**
     * get请求
     *
     * @param okHttpClient
     * @param url
     * @param headers      header参数
     * @return
     */
    public static String get(OkHttpClient okHttpClient, String url, Headers headers) {
        log.info("okHttpClient get url:{}.", url);
        Request request = new Request.Builder().url(url).headers(headers).get().build();

        String responseData = request(okHttpClient, url, request);
        log.info("okHttpClient get url:{},request responseData====> {}", url, responseData);
        return responseData;
    }

    /**
     * post请求，获取响应结果
     *
     * @param okHttpClient
     * @param url
     * @param requestEntity 请求体
     * @param headers
     * @return
     */
    public static <T> ResultVo<?> post(OkHttpClient okHttpClient, String url, T requestEntity, Headers headers) {
        log.info("okHttpClient post url:{}, body====> {}", url, requestEntity);
        MediaType mediaTypeJson = MediaType.parse(MEDIA_TYPE_JSON);

        RequestBody requestBody = RequestBody.create(GsonUtil.specialToJson(requestEntity), mediaTypeJson);
        Request request = new Request.Builder().url(url).headers(headers).post(requestBody).build();

        String responseData = request(okHttpClient, url, request);
        log.info("okHttpClient post url:{},post responseData====> {}", url, responseData);

        // 响应为空
        if (StringUtil.isEmpty(responseData)) {
            return new ResultVo<>(500, "响应结果为空", null);
        }

        // 校验响应是否是一个json
        if (!GsonUtil.validateJson(responseData)) {
            return new ResultVo<>(500, "响应结果不是一个json", responseData);
        }

        return GsonUtil.fromJson(responseData, ResultVo.class);
    }


    /**
     * post请求
     */
    @SneakyThrows
    public static <T, R> ResultVo<R> post(String url, T requestEntity, Class<R> returnClass) {
        // 使用默认的 okHttpClient
        OkHttpClient okHttpClient = getOkHttpClient();
        Headers headers = new Headers.Builder().build();
        // 执行post请求
        ResultVo<?> resultVo = post(okHttpClient, url, requestEntity, headers);

        // 处理结果
        if (resultVo.getCode() == 0) {
            Object data = resultVo.getData();
            if (data != null) {
                String jsonData = GsonUtil.specialToJson(data);
                R result = GsonUtil.fromJson(jsonData, returnClass);
                return new ResultVo<>(0, null, result);
            }
        }
        return new ResultVo<>(resultVo.getCode(), resultVo.getMessage(), null);
    }

    /**
     * 分页查询的post请求
     */
    public static <T extends PageRequest, R> ResultVo<PageBean<R>> postAndReturnPageBean(String url, T requestEntity, Class<R> returnClass) {
        // 使用默认的 okHttpClient
        OkHttpClient okHttpClient = getOkHttpClient();
        Headers headers = new Headers.Builder().build();
        // 如果需要自定义 okHttpClient或headers传参，可以调用以下方法
        ResultVo<?> resultVo = post(okHttpClient, url, requestEntity, headers);

        // 处理结果
        if (resultVo.getCode() == 0) {
            Object data = resultVo.getData();
            if (data != null) {
                String jsonData = GsonUtil.specialToJson(data);
                PageBean<R> result = GsonUtil.toPageBean(jsonData, returnClass);
                return new ResultVo<>(0, null, result);
            }
        }
        return new ResultVo<>(resultVo.getCode(), resultVo.getMessage(), null);
    }

    /**
     * 获取响应结果
     */
    private static String request(OkHttpClient okHttpClient, String url, Request request) {
        String responseData = "";
        try (Response response = okHttpClient.newCall(request).execute()) {
            if (response.body() != null) {
                return response.body().string();
            }
        } catch (Exception e) {
            log.error("okHttpClient getResponse error.url:{}", url, e);
        }

        return responseData;
    }
}


